#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import os
import random
import shutil
import time
import warnings

import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.distributed.rpc as rpc
import torch.distributed.autograd as dist_autograd
from torch.distributed.optim import DistributedOptimizer

from utils import find_free_port
from helper_class import AverageMeter, ProgressMeter
from mp_inception import DistInceptionV3


parser = argparse.ArgumentParser(description='PyTorch ImageNet Training with Model Parallelism.')
parser.add_argument('data', metavar='DIR',
                    help='path to dataset')
parser.add_argument('-j', '--workers', default=2, type=int, metavar='N',
                    help='number of data loading workers (default: 4)')
parser.add_argument('--epochs', default=90, type=int, metavar='N',
                    help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
                    help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=256, type=int,
                    metavar='N',
                    help='mini-batch size (default: 256), this is the total '
                         'batch size of all GPUs on the current node when '
                         'using Data Parallel or Distributed Data Parallel')
parser.add_argument('--split-size', default=256, type=int, metavar='N',
                    help='The number of splits when processing a single mini-batch samples.')
parser.add_argument('--lr', '--learning-rate', default=0.1, type=float,
                    metavar='LR', help='initial learning rate', dest='lr')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
                    help='momentum')
parser.add_argument('--wd', '--weight-decay', default=1e-4, type=float,
                    metavar='W', help='weight decay (default: 1e-4)',
                    dest='weight_decay')
parser.add_argument('-p', '--print-freq', default=50, type=int,
                    metavar='N', help='print frequency (default: 50)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
                    help='path to latest checkpoint (default: none)')
parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',
                    help='evaluate model on validation set')
parser.add_argument('--rank', default=-1, type=int,
                    help='node rank for distributed training')
parser.add_argument('--seed', default=None, type=int,
                    help='seed for initializing training. ')
parser.add_argument('--gpu', default=None, type=int,
                    help='GPU id to use.')


best_acc1 = 0


def save_checkpoint(state, is_best, filename='checkpoint.pth'):
    BEST_CKP = 'model_best.pth'
    rank = int(filename.split('_')[1][:-4])

    jobid = os.environ["SLURM_JOBID"]
    CHECKPOINT_DIR = f"./checkpoints/{jobid}"

    checkpoint_file = os.path.join(CHECKPOINT_DIR, filename)

    torch.save(state, checkpoint_file)
    if rank == 0:
        best_acc = 0.0
        if os.path.exists(os.path.join(CHECKPOINT_DIR, BEST_CKP)):
            hist_best = torch.load(os.path.join(CHECKPOINT_DIR, BEST_CKP))
            best_acc = hist_best['best_acc1']
        for ckp in os.listdir(CHECKPOINT_DIR):
            if 'checkpoint' not in ckp:
                continue
            hist_ckp = torch.load(os.path.join(CHECKPOINT_DIR, ckp))
            hist_acc = hist_ckp['best_acc1']
            if best_acc < hist_acc:
                shutil.copyfile(checkpoint_file,
                                os.path.join(CHECKPOINT_DIR, BEST_CKP))


def adjust_learning_rate(optimizer, epoch, args):
    """Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
    lr = args.lr * (0.1 ** (epoch // 30))
    if lr < 0.0001:
        lr = 0.0001
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr


def accuracy(output, target, topk=(1,)):
    """Computes the accuracy over the k top predictions for the specified values of k"""
    with torch.no_grad():
        maxk = max(topk)
        batch_size = target.size(0)

        _, pred = output.topk(maxk, 1, True, True)
        pred = pred.t()
        correct = pred.eq(target.view(1, -1).expand_as(pred))

        res = []
        for k in topk:
            correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
            res.append(correct_k.mul_(100.0 / batch_size))
        return res


def main():
    args = parser.parse_args()

    if args.seed is not None:
        random.seed(args.seed)
        torch.manual_seed(args.seed)
        cudnn.deterministic = True
        warnings.warn('You have chosen to seed training. '
                      'This will turn on the CUDNN deterministic setting, '
                      'which can slow down your training considerably! '
                      'You may see unexpected behavior when restarting '
                      'from checkpoints.')

    if args.gpu is not None:
        warnings.warn('You have chosen a specific GPU. This will completely '
                      'disable data parallelism.')

    # slurm settings.
    jobid = os.environ['SLURM_JOBID']
    rank = int(os.environ['SLURM_PROCID'])
    world_size = int(os.environ['SLURM_NPROCS'])
    hostfile = f"dist_url_{jobid}.txt"
    if rank == 0:
        # Use rank 0 machine as the master node.
        import socket
        ip = socket.gethostbyname(socket.gethostname())
        port = find_free_port()
        os.environ['MASTER_ADDR'] = ip
        os.environ['MASTER_PORT'] = f"{port}"
        master_info = f"{ip}:{port}"
        #print(f"Rank {rank}'s host url is {master_info}")
        with open(hostfile, 'w') as f:
            f.write(master_info)

        rpc.init_rpc('master', rank=rank, world_size=world_size)

        start_training(rank, args)
    elif rank == 1:
        import time
        while True:
            if not os.path.exists(hostfile):
                time.sleep(1)
            else:
                break
        with open(hostfile, 'r') as f:
            master_info = f.read()

        ip, port = master_info.split(':')
        print(f"Master INFO: {ip}:{port}")
        os.environ['MASTER_ADDR'] = ip
        os.environ['MASTER_PORT'] = port

        rpc.init_rpc(f"worker{rank}", rank=rank, world_size=world_size)

    # block until all rpcs finish.
    rpc.shutdown()


def start_training(rank, args):
    r"""
    The trainer creates a distributed InceptionV3 model and a DistributedOptimizer.
    Then, it performs training on the ImageNet 2012 data.
    """
    global best_acc1

    model = DistInceptionV3("worker1")

    # setup distributed optimizer
    opt = DistributedOptimizer(
        torch.optim.SGD,
        model.parameter_rrefs(),
        lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay
    )
    criterion = torch.nn.CrossEntropyLoss().cuda(0)

    if args.resume:
        if os.path.isfile(args.resume):
            print("loading checkpoint {}".format(args.resume).center(60, '='))
            checkpoint = torch.load(args.resume)
            args.start_epoch = checkpoint['epoch']
            best_acc1 = checkpoint['best_acc1']
            model.load_state_dict(checkpoint['state_dict'])
            print("Checkpoint loaded (epoch {})".format(args.start_epoch).center(60, '='))
        else:
            print("No checkpoint to be loaded at {}".format(args.resume))

    cudnn.benchmark = True

    train_dir = os.path.join(args.data, 'train')
    val_dir = os.path.join(args.data, 'val')
    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                     std=[0.229, 0.224, 0.225])

    train_dataset = datasets.ImageFolder(
        train_dir, transforms.Compose([
            transforms.RandomResizedCrop(299),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            normalize,
        ]))
    val_dataset = datasets.ImageFolder(
        val_dir, transforms.Compose([
            transforms.Resize(299),
            transforms.CenterCrop(299),
            transforms.ToTensor(),
            normalize,
        ]))

    train_loader = torch.utils.data.DataLoader(
        train_dataset, batch_size=args.batch_size, shuffle=True,
        num_workers=args.workers, pin_memory=True)
    val_loader = torch.utils.data.DataLoader(
        val_dataset, batch_size=args.batch_size, shuffle=False,
        num_workers=args.workers, pin_memory=True)

    if args.evaluate:
        validate(val_loader, model, criterion, args)
        return

    for epoch in range(args.start_epoch, args.epochs):
        #adjust_learning_rate(opt, epoch, args)
        print(f"Processing epoch {epoch}...")

        # train for one epoch.
        train(train_loader, model, criterion, opt, epoch, args)

        # evaluate on validation set.
        acc1 = validate(val_loader, model, criterion, args)
        is_best = acc1 > best_acc1
        best_acc1 = max(acc1, best_acc1)

        save_checkpoint({'epoch': epoch + 1,
                         'best_acc1': best_acc1,
                         'state_dict': model.state_dict()},
                        is_best, filename='checkpoin_{}.ckp'.format(rank))


def train(train_loader, model, criterion, optimizer, epoch, args):
    batch_time = AverageMeter('Time', ':6.3f')
    data_time = AverageMeter('Data', ':6.3f')
    losses = AverageMeter('Loss', ':.4e')
    top1 = AverageMeter('Acc@1', ':6.2f')
    top5 = AverageMeter('Acc@5', ':6.2f')
    progress = ProgressMeter(len(train_loader),
                             [batch_time, data_time, losses, top1, top5],
                             prefix="Epoch: [{}]".format(epoch))

    # switch to train mode
    model.train()

    end = time.time()
    print(f"begin processing samples....")
    for i, (images, target) in enumerate(train_loader):
        # measure data loading time
        data_time.update(time.time() - end)

        if args.gpu is not None:
            images = images.cuda(0, non_blocking=True)
        target = target.cuda(0, non_blocking=True)

        with dist_autograd.context() as context_id:
            # compute output. InceptionV3 will produce a auxiliary output here.
            # Use the solution from: https://github.com/pytorch/vision/issues/302
            # Three loss value solution: loss = loss1 + 0.3 * (loss2 + loss3)
            output, aux_output = model(images)
            loss1 = criterion(output, target)
            loss2 = criterion(aux_output, target)
            loss = loss1 + 0.4 * loss2

            # measure accuracy and record loss
            acc1, acc5 = accuracy(output, target, topk=(1, 5))
            losses.update(loss.item(), images.size(0))
            top1.update(acc1[0], images.size(0))
            top5.update(acc5[0], images.size(0))

            # compute gradient and do SGD step
            dist_autograd.backward(context_id, [loss])
            optimizer.step(context_id)

        # measure elapsed time
        batch_time.update(time.time() - end)
        end = time.time()

        if i % args.print_freq == 0:
            progress.display(i)


def validate(val_loader, model, criterion, args):
    batch_time = AverageMeter('Time', ':6.3f')
    losses = AverageMeter('Loss', ':.4e')
    top1 = AverageMeter('Acc@1', ':6.2f')
    top5 = AverageMeter('Acc@5', ':6.2f')
    progress = ProgressMeter(len(val_loader), [batch_time, losses, top1, top5],
                             prefix='Test: ')

    # switch to evaluate mode
    model.eval()

    with torch.no_grad():
        end = time.time()
        for i, (images, target) in enumerate(val_loader):
            target = target.cuda(0, non_blocking=True)

            # compute output
            output = model(images)
            loss = criterion(output, target)

            # measure accuracy and record loss
            acc1, acc5 = accuracy(output, target, topk=(1, 5))
            losses.update(loss.item(), images.size(0))
            top1.update(acc1[0], images.size(0))
            top5.update(acc5[0], images.size(0))

            # measure elapsed time
            batch_time.update(time.time() - end)
            end = time.time()

            if i % args.print_freq == 0:
                progress.display(i)

        # TODO: this should also be done with the ProgressMeter
        print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}'
              .format(top1=top1, top5=top5))

    return top1.avg


if __name__ == '__main__':
    main()
